package com.dxf.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    // 用于记录和管理所有客户端的ChannelGroup
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
            // 获取客户端传输过来的消息
        String content = textWebSocketFrame.text();
        log.info("接收到的数据：{}",content);

        //ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器主动推送消息给指定客户端"));//给单个客户端发送消息

        for(Channel channel : clients) {//给所有客户端发送消息
            // 不能直接writeAndFlush收到的content字符串信息，必须封装到frame载体中输出
            channel.writeAndFlush(new TextWebSocketFrame("系统消息：" + content));
        }
        //clients.writeAndFlush(new TextWebSocketFrame("系统消息：" + content));//给所有客户端发送消息，效果同上for循环

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
        ChannelId id = ctx.channel().id();
        System.out.println("客户端id-------"+id+"-----连接");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        clients.remove(ctx.channel());
    }
}
